import React, { useState, useEffect } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Search, Plus, Edit, Trash2, ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react";
import StandardForm from "@/components/knowledge-base/StandardForm";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Badge } from "@/components/ui/badge";

// 状态标签配置
const getStatusConfig = (status) => {
  const configs = {
    active: { label: "现行", color: "bg-green-100 text-green-700" },
    inactive: { label: "废止", color: "bg-red-100 text-red-700" },
    superseded: { label: "被替代", color: "bg-yellow-100 text-yellow-700" },
  };
  return configs[status] || { label: status, color: "bg-gray-100 text-gray-700" };
};

// 类别标签配置
const getCategoryLabel = (category) => {
  const labels = {
    national: "国家标准",
    industry: "行业标准",
    local: "地方标准",
    enterprise: "企业标准",
  };
  return labels[category] || category;
};

export default function Standards({
  standards,
  onSubmit,
  onDelete,
  searchTerm,
  setSearchTerm,
  handleFilteredCountChange,
}) {
  const [showForm, setShowForm] = useState(false);
  const [editingStandard, setEditingStandard] = useState(null);
  const [filteredStandards, setFilteredStandards] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

  // 筛选数据
  useEffect(() => {
    let filtered = standards;
    
    if (searchTerm) {
      filtered = filtered.filter(
        (standard) =>
          standard.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
          standard.code?.toLowerCase().includes(searchTerm.toLowerCase()) ||
          standard.description?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }
    
    setFilteredStandards(filtered);
    handleFilteredCountChange("standards", filtered.length);
    setCurrentPage(1); // 筛选后重置页码
  }, [standards, searchTerm, handleFilteredCountChange]);

  // 分页处理函数
  const handlePageChange = (pageNum) => {
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
    }
  };

  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1); // 切换每页条数时重置到第一页
  };

  // 计算分页数据
  const totalItems = filteredStandards.length;
  const totalPages = Math.ceil(totalItems / itemsPerPage);
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredStandards.slice(indexOfFirstItem, indexOfLastItem);

  // 渲染分页组件（使用提供的统一模式）
  const renderPagination = () => (
    <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
      <div className="text-sm text-gray-500">
        共 {totalItems} 条数据，显示
        {(currentPage - 1) * itemsPerPage + 1} 到
        {Math.min(currentPage * itemsPerPage, totalItems)} 条
      </div>
      <div className="flex items-center gap-2">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm" className="h-8">
              每页 {itemsPerPage} 条
              <MoreHorizontal className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {[5, 10, 20, 50].map((count) => (
              <DropdownMenuItem
                key={count}
                onClick={() => handleItemsPerPageChange(count)}
              >
                {count} 条/页
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        <div className="flex items-center gap-1">
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1}
          >
            <ChevronLeft className="h-4 w-4" />
            <span className="sr-only">上一页</span>
          </Button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "default" : "outline"}
                size="icon"
                className="h-8 w-8"
                onClick={() => handlePageChange(pageNum)}
              >
                {pageNum}
              </Button>
            );
          })}
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            <ChevronRight className="h-4 w-4" />
            <span className="sr-only">下一页</span>
          </Button>
        </div>
      </div>
    </div>
  );

  const handleEdit = (standard) => {
    setEditingStandard(standard);
    setShowForm(true);
    setTimeout(() => {
      const formElement = document.getElementById("standard-form");
      if (formElement) {
        formElement.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    }, 250);
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingStandard(null);
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-col md:flex-row gap-3 items-start md:items-center">
        <div className="relative flex-1 w-full">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <Input
            placeholder="搜索标准名称或编号..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10 h-10 border-gray-200 focus:border-blue-400 focus:ring-1 focus:ring-blue-400 transition-all"
          />
        </div>

        <Button
          onClick={() => {
            setEditingStandard(null);
            setShowForm(true);
          }}
          className="bg-green-600 hover:bg-green-700 h-10 px-4 transition-all shadow-sm hover:shadow"
        >
          <Plus className="w-4 h-4 mr-2" />
          新建标准规范
        </Button>
      </div>

      {showForm && (
        <StandardForm
          id="standard-form"
          standard={editingStandard}
          onSubmit={onSubmit}
          onCancel={handleCancel}
        />
      )}

      {filteredStandards.length > 0 ? (
        <div className="rounded-lg border border-gray-200 overflow-hidden shadow-sm">
          {/* 表格 */}
          <div className="overflow-x-auto">
            <Table>
              <TableHeader className="bg-gray-50 border-b border-gray-200">
                <TableRow>
                  <TableHead className="w-[250px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    标准名称
                  </TableHead>
                  <TableHead className="min-w-[150px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    标准编号
                  </TableHead>
                  <TableHead className="min-w-[150px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    发布单位
                  </TableHead>
                  <TableHead className="w-[100px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    发布年份
                  </TableHead>
                  <TableHead className="w-[100px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    状态
                  </TableHead>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    类别
                  </TableHead>
                  <TableHead className="w-[100px] py-3 px-4 text-right text-sm font-semibold text-gray-700">
                    操作
                  </TableHead>
                </TableRow>
              </TableHeader>

              <TableBody>
                {currentItems.map((standard) => {
                  const statusConfig = getStatusConfig(standard.status);
                  return (
                    <TableRow
                      key={standard.id}
                      className="transition-colors duration-150 border-b border-gray-100 last:border-0"
                    >
                      <TableCell className="py-3 px-4">
                        <div className="font-medium text-gray-900">
                          {standard.name || "未命名标准"}
                        </div>
                      </TableCell>
                      <TableCell className="py-3 px-4 text-gray-700">
                        {standard.code || "N/A"}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-gray-700">
                        {standard.issuingAuthority || "未知"}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-gray-700">
                        {standard.publicationYear || "未知"}
                      </TableCell>
                      <TableCell className="py-3 px-4">
                        <Badge className={`${statusConfig.color} px-2 py-0.5 text-xs rounded-md`}>
                          {statusConfig.label}
                        </Badge>
                      </TableCell>
                      <TableCell className="py-3 px-4">
                        <Badge variant="secondary" className="text-xs bg-gray-100 text-gray-700">
                          {getCategoryLabel(standard.category)}
                        </Badge>
                      </TableCell>
                      <TableCell className="py-3 px-4 text-right">
                        {/* 操作下拉菜单 */}
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-8 w-8 text-gray-600 hover:text-blue-600 hover:bg-blue-50 transition-colors"
                            >
                              <MoreHorizontal className="w-4 h-4" />
                              <span className="sr-only">打开操作菜单</span>
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end" className="w-[140px] border-gray-200">
                            <DropdownMenuItem
                              onClick={() => handleEdit(standard)}
                              className="cursor-pointer hover:bg-blue-50 hover:text-blue-700"
                            >
                              <Edit className="w-4 h-4 mr-2" />
                              编辑
                            </DropdownMenuItem>
                            <DropdownMenuSeparator className="bg-gray-100" />
                            <DropdownMenuItem
                              onClick={() => onDelete(standard.id)}
                              className="text-red-600 cursor-pointer hover:bg-red-50"
                            >
                              <Trash2 className="w-4 h-4 mr-2" />
                              删除
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </div>

          {/* 分页组件 */}
          {renderPagination()}
        </div>
      ) : (
        <div className="text-center py-16 px-4 text-gray-500 border rounded-lg bg-gray-50 border-gray-200">
          <Search className="w-10 h-10 mx-auto mb-4 text-gray-300" />
          <h3 className="text-lg font-medium text-gray-600 mb-2">
            没有找到匹配的标准规范
          </h3>
          <p className="text-sm text-gray-400">
            建议调整搜索关键词后重试
          </p>
        </div>
      )}
    </div>
  );
}